trigger JobAppSharingTrigger on Job_Application__c (after insert, after update) {
	
	//TODO: Instatiate two job application lists called "interviewJobApps" and "nonInterviewJobApps" 
    List<Job_Application__c> interviewJobApps = new List<Job_Application__c>();
	List<Job_Application__c> nonInterviewJobApps = new List<Job_Application__c>();

	//TODO: Create a for loop to loop through the triggering job applications
    for (Job_Application__c jobApp : Trigger.new) {
		//TODO: If the job application stage = "Schedule Interviews" and it was not set to that value before, 
		//then add the record to the interviewJobApps list
		if ((jobApp.Stage__c == 'Schedule Interviews') && (Trigger.isInsert || (Trigger.oldMap.get(jobApp.id).Stage__c != 'Schedule Interviews'))) {
			interviewJobApps.add (jobApp);

        } else if (jobApp.Stage__c != 'Schedule Interviews') {
		    //TODO: If not, and the stage is not "Schedule Interviews" then add it to the nonInterviewJobApps list
		    nonInterviewJobApps.add (jobApp);
		} // else do nothing with the record
	
    }
	//TODO: Call the appropriate method from the JobAppSharing class to add sharing for the records in the interviewJobApps list
	JobAppSharing.createSharing(interviewJobApps,'Position_Interviewer__c','Edit');
	
	//TODO: Then change the sharing for the nonInterviewJobApps to read-only
	JobAppSharing.createSharing(nonInterviewJobApps,'Position_Interviewer__c','Read');
	
	if (Trigger.isInsert){
		// Share with position hiring manager if available
		List<Job_Application__c> jobApps = [select j.id,j.position__c,j.candidate__c,j.position__r.hiring_manager__c from Job_Application__c j where j.ID IN :Trigger.newMap.keySet() and j.position__r.hiring_manager__c != null];
		JobAppSharing.createSharing(jobApps,'Hiring_Manager__c','Edit');
	}
}